//
//  NewCurveLineChartView.m
//  CoollangTennisBall
//
//  Created by Coollang on 2017/8/29.
//  Copyright © 2017年 Coollang-YF. All rights reserved.
//

#import "NewCurveLineChartView.h"
#import <Masonry/Masonry.h>

static const CGFloat kAnimationDuration = 0.6f;

@interface NewCurveLineChartView ()<ChartViewDelegate,IChartAxisValueFormatter>

@property (nonatomic, strong) LineChartView *lineChartView;

@property (nonatomic, strong) NSArray *lineItems;

@property (nonatomic, strong) NSArray *xValueArr;

@end

@implementation NewCurveLineChartView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.lineChartView = [[LineChartView alloc] initWithFrame:frame];
        [self addSubview:self.lineChartView];
        [self.lineChartView mas_makeConstraints:^(MASConstraintMaker *make) {
             make.edges.equalTo(self);
        }];
        self.showXAxis = YES;
    }
    return self;
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super initWithCoder:aDecoder]) {
        self.lineChartView = [[LineChartView alloc] init];
        [self addSubview:self.lineChartView];
        [self.lineChartView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self);
        }];
        self.showXAxis = YES;
    }
    return self;
}

- (void)ConfigerTheme:(kChartLineViewStyle)style {
    
    self.style = style;
    
    self.lineChartView.delegate = self;
    self.lineChartView.descriptionText = @" ";
    self.lineChartView.noDataText = @" ";
    self.lineChartView.dragEnabled = YES;
    self.lineChartView.highlightPerTapEnabled = YES;
    self.lineChartView.chartDescription = nil;
    
//   1.设置交互样式
    self.lineChartView.scaleYEnabled = NO;//取消Y轴缩放
    self.lineChartView.doubleTapToZoomEnabled = NO;//取消双击缩放
    self.lineChartView.dragEnabled = YES;//启用拖拽图标
    self.lineChartView.dragDecelerationEnabled = YES;//拖拽后惯性效果
    [self.lineChartView setScaleEnabled:NO];
    self.lineChartView.pinchZoomEnabled = NO;

//    2.设置X轴样式
    [self configureXAxis];
    
    switch (style) {
        case kTennisBaseStyle:{
            self.lineChartView.legend.form = ChartLegendFormLine;
            self.lineChartView.legend.font = [UIFont systemFontOfSize:12];
            self.lineChartView.legend.position = ChartLegendPositionAboveChartRight;
            [self configerYAxis:self.lineChartView.leftAxis];
            [self configerYAxis:self.lineChartView.rightAxis];
            self.lineChartView.xAxis.enabled = _showXAxis;
            self.lineChartView.legend.enabled = NO;
            
        }
            break;
        default:
            break;
    }
}

// 带自适应的最大值最小值得Y轴设置
- (void)defaultSuitableSettingCompare:(CGFloat)minValue maxValue:(CGFloat)maxValue setAxis:(kAxisType)axisType labelCount:(NSInteger)count show:(BOOL)isShow drawGridLinesEnabled:(BOOL)drawGridLines axisLineColor:(UIColor *)axisColor{
    
    ChartYAxis *yAxis = (axisType == kAxisLeft) ? self.lineChartView.leftAxis : self.lineChartView.rightAxis;
    //Y轴label数量，数值不一定，如果forceLabelsEnabled等于YES, 则强制绘制制定数量的label, 但是可能不平均
    yAxis.labelCount = count;
    yAxis.axisMinValue = minValue; //- maxValue/8 > -2 ? -2: - maxValue/8;
    yAxis.axisMaxValue = maxValue;//(maxValue - yAxis.axisMinValue)/yAxis.labelCount * (yAxis.labelCount + 1) > 50 ? (maxValue - yAxis.axisMinValue)/yAxis.labelCount * (yAxis.labelCount + 1) : 50;
    yAxis.drawGridLinesEnabled = drawGridLines;
    yAxis.labelPosition = YAxisLabelPositionOutsideChart;
    yAxis.enabled = isShow;
    
    if (axisColor) { yAxis.axisLineColor = axisColor;}
    
    if (!isShow) { yAxis.labelTextColor = [UIColor clearColor];}
}

// 设置Y轴的默认样式
- (void)configerYAxis:(ChartYAxis *)yAxis {
    yAxis.gridLineWidth = 0.3;
    [yAxis removeAllLimitLines];
    yAxis.labelTextColor = [UIColor colorWithHex:0x7c7b80 alpha:0.5];
    yAxis.labelFont = [UIFont systemFontOfSize:8];
    yAxis.labelPosition = YAxisLabelPositionOutsideChart;
    
    yAxis.valueFormatter = [[ChartDefaultAxisValueFormatter alloc] initWithFormatter:[[NSNumberFormatter alloc] init]];
    ChartDefaultAxisValueFormatter *axisValueFormatter =(ChartDefaultAxisValueFormatter *)yAxis.valueFormatter;
    axisValueFormatter.formatter.maximumFractionDigits = 1;
    axisValueFormatter.formatter.negativeFormat = @"";
    axisValueFormatter.formatter.positiveFormat = @"";
}

- (void)drawLineWithCurveLineItemArr:(NSArray <CurveLineItem *> *)lineItemes showAnimation:(BOOL)animation {
    
    [lineItemes enumerateObjectsUsingBlock:^(CurveLineItem *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        obj.index = idx;
    }];
    self.lineItems = lineItemes;
    
    // 绘制曲线
    for (NSInteger i = 0; i < lineItemes.count; i++) {
        [self drawLineWithCurveLineItem:lineItemes[i]];
    }
    if (animation) {
        [self.lineChartView animateWithXAxisDuration:kAnimationDuration];
    }
    
    
}

// 绘制线条
- (void)drawLineWithCurveLineItem:(CurveLineItem *)lineItem {
    
    NSMutableArray *dataEntryArr = [[NSMutableArray alloc] init];
    
    // 设置xValus
    for (NSInteger i = 0; i < lineItem.yValues.count; i++) {
        NSNumber *yValue = lineItem.yValues[i];
        ChartDataEntry *dataEentry = [[ChartDataEntry alloc] initWithX:i y:[yValue doubleValue] data:nil];
        if (lineItem.xValues.count == lineItem.yValues.count) {
            dataEentry.x = [lineItem.xValues[i] integerValue];
        }
        
        [dataEntryArr addObject:dataEentry];
    }
  
    LineChartDataSet *dataSet = nil;
    
    if (self.lineChartView.data) {
        if (self.lineChartView.data.dataSetCount > lineItem.index) {
            dataSet = (LineChartDataSet *)self.lineChartView.data.dataSets[lineItem.index];
            dataSet.values = dataEntryArr;
        }else {
            dataSet = [[LineChartDataSet alloc] initWithValues:dataEntryArr label:lineItem.dataSet];
            [self configLineDataSet:lineItem withlineDataset:dataSet];
            [self.lineChartView.data addDataSet:dataSet];
        }
        [self.lineChartView.data notifyDataChanged];
        [self.lineChartView notifyDataSetChanged];
    }else {
        dataSet = [[LineChartDataSet alloc] initWithValues:dataEntryArr label:lineItem.dataSet];
        [self configLineDataSet:lineItem withlineDataset:dataSet];
        self.lineChartView.data = [[LineChartData alloc] initWithDataSets:@[dataSet]];
    }
    
}

// 配置具体线条颜色
- (void)configLineDataSet:(CurveLineItem *)lineItem withlineDataset:(LineChartDataSet *)lineDataSet {
    
    switch (self.style) {
        case kTennisBaseStyle:{
            lineDataSet.mode = LineChartModeLinear;
            lineDataSet.cubicIntensity = 0.2;
            lineDataSet.lineWidth = lineItem.lineWidth;
            lineDataSet.drawCirclesEnabled = lineItem.yValues.count == 1 ? YES:NO;
            lineDataSet.circleRadius = 3.0;
            lineDataSet.drawFilledEnabled = lineItem.showFull;
            lineDataSet.drawCubicEnabled = YES;
            lineDataSet.drawValuesEnabled = NO;
            lineDataSet.highlightColor = (lineItem.lineColor != nil ? lineItem.lineColor : [UIColor whiteColor]);
            [lineDataSet setColor:(lineItem.lineColor != nil ? lineItem.lineColor : [UIColor whiteColor])];
            lineDataSet.fillColor = lineItem.fullColor;
            lineDataSet.axisDependency = lineItem.yAxisDependency;
        }
            break;
        default:
            break;
    }
}

// X轴上面需要显示的数据
- (void)configuerXAxisValus:(NSArray *)xValues {
    if (xValues.count > 0){
        self.xValueArr = xValues;
        self.lineChartView.xAxis.labelCount = xValues.count;
        self.lineChartView.xAxis.forceLabelsEnabled = YES;
//        self.lineChartView.xAxis.valueFormatter = self;
    }
}

- (void)configureXAxis
{
    ChartXAxis *xAxis = self.lineChartView.xAxis;
    xAxis.enabled = YES;
    xAxis.labelFont = [UIFont systemFontOfSize:9.f];
    xAxis.labelTextColor = [UIColor colorWithHex:0x7c7b80 alpha:0.5];
    xAxis.drawGridLinesEnabled = NO;
    xAxis.drawAxisLineEnabled = NO;
    xAxis.axisLineWidth = 0.5;
    xAxis.axisMinimum = 0.0;
    xAxis.labelPosition = XAxisLabelPositionBottom;
    
}

- (NSString *)stringForValue:(double)value
                        axis:(ChartAxisBase *)axis
{
    NSInteger index = (value + 0.0001) / ((axis.axisMaxValue * 1.0)/(axis.entryCount - 1));
    return [self.xValueArr[(int)index % self.xValueArr.count] stringValue];
}

@end


@implementation CurveLineItem

- (instancetype)initWithLineWidth:(CGFloat)lineWidth color:(UIColor *)lineColor fullColor:(UIColor *)fullColor xValues:(NSArray *)xValues yValues:(NSArray *)yValues {
    if (self = [super init]) {
        self.xValues = xValues;
        self.yValues = yValues;
        self.fullColor = fullColor;
        self.lineColor = lineColor;
        self.lineWidth = lineWidth;
        self.showFull = YES;
        self.showHighlightLine = NO;
        self.dataSet = @"";
    }
    return self;
}


@end
